package com.lemonPiggy.UDForm.controller;

import com.lemonPiggy.UDForm.domain.MongoTest;
import com.lemonPiggy.UDForm.service.IMongoDBService;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mongo")
public class MongoDBController extends BaseController {

    @Autowired
    private MongoTemplate mongoTemplate;
   @Autowired
   private IMongoDBService mongoDBService;

    @PostMapping("/saveUDForm")
    public R saveUDForm(Map map, String table){
        BasicDBObject basicDBObject = new BasicDBObject();
        basicDBObject.put("name", "李四");
        basicDBObject.put("age",112);
        mongoTemplate.insert(basicDBObject,"Wang");
        return R.ok();
    }

    @DeleteMapping("/delete")
    public String delete(){
        MongoCollection<Document> UDForm = mongoTemplate.getCollection("Wang");
        BasicDBObject basicDBObject = new BasicDBObject("name", "李四");
        for (int i = 0; i <5 ; i++) {
            UDForm.deleteOne(basicDBObject);
        }
        return "成功！！";
    }
    @PostMapping("/updateForm")
    public String updateForm(){
        MongoCollection<Document> UDForm = mongoTemplate.getCollection("UDForm");
        BasicDBObject b = new BasicDBObject();
        UDForm.updateOne(Filters.eq("id    ","610b4ff399336b5a9e2e3fa3"),new BasicDBObject("$set",new BasicDBObject("job","吃饭")));
        return null;
    }
    @GetMapping("/selectAll")
    public void selectAll(){
        MongoCollection<Document> UDForm = mongoTemplate.getCollection("UDForm");
    }

    @PostMapping("/save")
    public MongoTest save(MongoTest test){
        mongoDBService.save(test);
        return test;
    }
    @GetMapping("/findOne")
    public MongoTest findOne(Integer id){
          return   mongoDBService.findById(id);
    }
    @DeleteMapping("/remove")
    public String remove(Integer id){
        try{
            mongoDBService.delete(id);
            return "成功";
        }catch (Exception e){
            e.printStackTrace();
            return "失败";
        }
    }
    @PatchMapping("/update")
    public MongoTest update(MongoTest mongoTest){
        mongoDBService.update(mongoTest);
        return mongoTest;
    }
    @GetMapping("/findAll")
    public List<MongoTest> findAll(){
        List<MongoTest> list = mongoDBService.findAll();
        return list;
    }


}
